package com.znf4.controller.login;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.znf4.cache.redis.RedisUtils;
import com.znf4.config.SystemConfig;
import com.znf4.constants.CommonConst;
import com.znf4.controller.util.WeixinUtil;
import com.znf4.user.info.entity.UserInfo;
import com.znf4.user.info.server.UserInfoServer;
import com.znf4.utils.StringUtil;


/**
 * 微信授权
 */
@Controller
@RequestMapping("/wx/auth/")
public class OAuthController {

	@Autowired
	private UserInfoServer userInfoService;
	
	
	private static final Logger logger = LoggerFactory.getLogger(OAuthController.class);
	
	
	@RequestMapping(value = "index")
	public String index() throws Exception {
		
		return "index";
	}
	
	

	@RequestMapping(value = "toAuth")
	public String toAuth() throws Exception {
		
		String appId =  SystemConfig.WEIXIN_GZH_APP_ID ;
		String url = WeixinUtil.getoAuthUrlBy_snsapi_base( SystemConfig.WEIXIN_GZH_REDIRECT_URL , appId  );
		logger.info("==================================>toAuthUrl：" + url );
		return "redirect:" + url ;
//		response.sendRedirect(url);
	}

	/**
	 * 通过code获取openId，成功后则去获取用户信息
	 * 跳转不同的页面
	 * 
	 * @param state
	 * @param code
	 * @param redirectType
	 * @param request
	 * @param mm
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "authRedirect", method = RequestMethod.GET)
	@ResponseBody
	public String authRedirect(@RequestParam("state") String state, @RequestParam(value = "code", required = false) String code ,
			HttpServletRequest request, HttpServletResponse response) throws IOException {

		String appId = SystemConfig.WEIXIN_GZH_APP_ID;
		String appSecret = SystemConfig.WEIXIN_GZH_APP_SECRET;
		// 获取openId
		String openid = WeixinUtil.getOpenid(code, appId, appSecret);

		if (!StringUtil.isNotNull(openid)) {
			logger.info("=========================>openId 获取异常");
			return "";
		}
		logger.info("公众号里面授权到的openId[{}]", openid);

		
		// 根据appId查询支付信息
		UserInfo userInfo = new UserInfo();
		userInfo.setOpen_id(openid);
		userInfo = userInfoService.queryOne(userInfo);

		// 注入session
		request.getSession().setAttribute(CommonConst.WX_OPEN_ID, openid);
		request.getSession().setAttribute(CommonConst.WX_CODE, code);

		if (userInfo == null) { // 跳转到注册页面
			logger.info("=========================>openId :" + openid + ",open_id 没有维护到数据库");
//			return "redirect:" + String.format(SystemConfig.REGISTER_URL, redirectType);
			return "noBinding"  ;
		}
		//
		logger.info("用户已绑定过，直接跳转到对应页面");
		logger.info("公众号里面openId[{}],查找到用户帐号[{}]", openid, userInfo.getUsername() );
		
		return "binding" ;
		
	}

	/**
	 * 支付授权<br/>
	 * 通过code换取网页授权access_token，成功后则去获取用户信息
	 * 
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "authRedirectPay/{redirectType}", method = RequestMethod.GET)
	public String authRedirectPay(@RequestParam("state") String state, @RequestParam(value = "code", required = false) String code, @PathVariable(value = "redirectType") String redirectType, HttpServletRequest request, ModelMap mm) throws IOException {
		String payAppId = SystemConfig.WEIXIN_PAY_APP_ID;
		String payAppSecret = SystemConfig.WEIXIN_PAY_APP_SECRET;
		// 如果不使用平台公众号
		Map<String, String> appInfo = (Map<String, String>) RedisUtils.get("APPID" + redirectType);
		if (appInfo != null) {
			payAppId = appInfo.get("payAppId");
			payAppSecret = appInfo.get("payAppSecret");
			logger.info("====使用商户自己公众号===appId:" + payAppId);
		}

		String openid = WeixinUtil.getOpenidToPay(code, payAppId, payAppSecret);// 静默方式请求，只获取用户openid
		if (StringUtil.isNotNull(openid)) {
			// return "redirect:" + SystemConfig.GATEWAY_URL +
			// "oneCodePay/h5pay/" + redirectType + "?openid=" + openid;
//			return "redirect:" + SystemConfig.GATEWAY_URL + "oneCodePay/h5pay/tqNo?tqNo=" + redirectType + "&openid=" + openid;
		}
		logger.error("==>openid为空，code:" + code);
		mm.put("errMsg", "微信授权失败");
		return "tq/error";
	}

	/**
	 * 支付授权(动态跳转URL)<br/>
	 * 通过code换取网页授权access_token，成功后则去获取用户信息
	 * 
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "authRedirectPayUrl/{redirectType}/{level}", method = RequestMethod.GET)
	public String authRedirectPayUrl(@RequestParam("state") String state, @RequestParam(value = "code", required = false) String code, @PathVariable(value = "redirectType") String redirectType, @PathVariable(value = "level") String level, HttpServletRequest request, ModelMap mm) throws IOException {
		String payAppId = SystemConfig.WEIXIN_PAY_APP_ID;
		String payAppSecret = SystemConfig.WEIXIN_PAY_APP_SECRET;
		// 如果不使用平台公众号
		Map<String, String> appInfo = (Map<String, String>) RedisUtils.get("APPID" + redirectType);
		if (appInfo != null) {
			payAppId = appInfo.get("payAppId");
			payAppSecret = appInfo.get("payAppSecret");
			logger.info("====使用商户自己公众号===appId:" + payAppId);
		}

		String openId = WeixinUtil.getOpenidToPay(code, payAppId, payAppSecret);// 静默方式请求，只获取用户openid
		if (StringUtil.isNotNull(openId)) {
			// return "redirect:" + SystemConfig.GATEWAY_URL +
			// "oneCodePay/h5pay/" + redirectType + "?openid=" + openid;
			logger.info("获取到openId：" + openId);
//			return "redirect:" + SystemConfig.GATEWAY_URL + "oneCodePay/h5pay/getAuth?level=" + level + "&openId=" + openId;
		}
		logger.error("==>openid为空，code:" + code);
		mm.put("errMsg", "微信授权失败");
		return "tq/error";
	}

	/**
	 * 上传图片权限配置
	 * 
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "getConfigInfo", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> getConfigInfo(@RequestParam("url") String url, HttpServletRequest request, ModelMap mm) throws Exception {
		logger.info("getConfigInfo");
		// JS权限验证配置
		Map<String, String> map = WeixinUtil.getToken(url, request);
		logger.info("返回map：" + map.toString());
		return map;
	}

	/**
	 * 上传图片
	 * 
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "uploadImage", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> uploadImage(@RequestParam("mediaId") String mediaId, @RequestParam("fileName") String fileName, HttpServletRequest request, ModelMap mm) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		logger.info("uploadImage，mediaId：" + mediaId + ",fileName:" + fileName);
		// 上传图片至FTP
		String filePath = WeixinUtil.class.getResource("/").getPath();
		fileName = StringUtil.get32UUID() + fileName + ".jpg";
		map = WeixinUtil.downloadPic(mediaId, fileName, filePath);
		logger.info("返回map：" + map.toString());
		return map;
	}
	
	
	
	
	
	
	
	
	
	
	
}
